// src/api/axios.js
import axios from 'axios';
import { ElMessage } from 'element-plus'
import { ElLoading } from 'element-plus'
// 创建axios实例
// console.log(import.meta.env.VITE_APP_BASE_API,'99999')

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 你的API基础路径
  timeout: 50000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json' // 全局设置 Content-Type
  }
});
var loading 


// 请求拦截器
service.interceptors.request.use(
  config => {
      // 在发送请求之前做些什么，例如添加 token
    if(true){
      loading = ElLoading.service({
        lock: true,
        background: 'rgba(0, 0, 0, 0.16)',
        // fullscreen: true,
        spinner: 'el-icon-loading'
      });
    }
    const token = localStorage.getItem('token');
    config['headers']['token'] = token || '';
    config['headers']['time'] = new Date().getTime();
    config['headers']['key'] = 'e5cd7e4891bf95d1d19206ce24a7b32e';
    
    return config;
  },
  error => {
      // 处理请求错误
      if (loading) {
        loading.close();
      }
      console.log(error,'拦截异常');
      return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
      if (loading) {
        loading.close();
      }
      // 对响应数据做点什么
      const res = response.data;

      if(res){
        if(res.code === 200 || res.code === 201){
          return res;
        }else{
          console.log('api-2');
          // 处理业务错误
          ElMessage(
            {
              message:'接口异常',
              type: 'error',
            }
          );
          return Promise.reject(new Error(res.message || 'Error'));
        }

      }else{
        ElMessage(
          {
            message:'相应异常' ,
            type: 'error',
          }
        );
      }
      
      
  },
  error => {
      // 处理响应错误
      if (loading) {
        loading.close();
      }
      ElMessage.error("服务器/网络异常");
      return Promise.reject(error);
  }
);


// 封装请求方法
const request = {
  get(url, params = {}) {
      return service.get(url, { params });
  },
  post(url, data = {}) {
      return service.post(url, data);
  },
  put(url, data = {}) {
      return service.put(url, data);
  },
  delete(url, params = {}) {
      return service.delete(url, { params });
  },
  upload(url, file, config = {}) {
    const formData = new FormData();
    formData.append('file', file);
    const defaultConfig = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    };
    const finalConfig = { ...defaultConfig, ...config };
    return service.post(url, formData, finalConfig);
  }
};

export default request;